﻿#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QPainter>
#include <QPaintEvent>

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    InitDashboard();
    ui->widget_rpm->installEventFilter(this);
    timer1 = new QTimer(this);
    connect(timer1,&QTimer::timeout,this,&MainWindow::TimerEvent);
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::InitDashboard()
{
    _dashboard_rpm=new HyDashboard();
    _dashboard_rpm->Attach(ui->widget_rpm);
    _dashboard_rpm->SetDialTitle(QStringLiteral("转速(r/min)"));
    _dashboard_rpm->SetScaleUnit("");
    _dashboard_rpm->SetDialRange(0,9000);
    _dashboard_rpm->SetStyle(HyDashboard::StyleType::STYLE_DEFAULT);
    _dashboard_rpm->SetScaleNumberFontSize(12);
    _dashboard_rpm->SetDialValue(0);
}

bool MainWindow::eventFilter(QObject *object, QEvent *event)
{
    if(event->type() == QEvent::Paint && object == ui->widget_rpm)
    {
        QPainter pt_rpm(ui->widget_rpm);
        _dashboard_rpm->SetDialCenter(ui->widget_rpm->width()/2,ui->widget_rpm->height()/2);
        _dashboard_rpm->SetDialSide(qMin(ui->widget_rpm->width(),ui->widget_rpm->height()));
        pt_rpm.save();
        _dashboard_rpm->DrawDial(&pt_rpm);
        pt_rpm.restore();
    }
    return QWidget::eventFilter(object, event); // 其它绘图事件交给父类处理
}

void MainWindow::TimerEvent()
{
    if(nowRpm>9000)
        nowRpm = 0;
    else
        nowRpm+=100;
    _dashboard_rpm->SetDialValue(nowRpm);
    //ui->widget_rpm->update(); // 更新控件
}

void MainWindow::on_pushButton_clicked()
{
    if(timer1->isActive())
        timer1->stop();
    else
        timer1->start(1000);
}

